package com.dwyinyuan.infrastructure.util.interceptor;

import com.dwyinyuan.infrastructure.util.enums.*;
import com.dwyinyuan.infrastructure.util.exception.*;
import com.google.common.util.concurrent.*;
import lombok.extern.slf4j.*;
import org.springframework.stereotype.*;
import org.springframework.web.servlet.*;

import javax.servlet.http.*;


/**
 * 微信公众号：笛舞音缘
 * <p>
 * 全局限流拦截器
 * <p>
 * Created by andy  on 2020-12-16.
 */
@Slf4j
@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    /**
     * 限流器实例(QPS限制为10)
     */
    private static final RateLimiter rateLimiter = RateLimiter.create(1);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 尝试获取令牌
        if (!rateLimiter.tryAcquire()) {
            log.error("系统已被限流...");

            throw new BusinessException(ErrorCodeEnum.RATE_LIMIT_ERROR);
        }

        return true;
    }
}
